package com.authine.cloudpivot.ext.controller;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.service.ThirdPartyAppService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * 实现了最简单的免密登录（免登）功能
 */
@Api(value = "第三方企业应用免登", tags = "01::EXTAPI::第三方企业应用免登")
@RestController
@RequestMapping("/api/thirdPartyApp")
@Slf4j
public class ThirdPartyAppController extends BaseController {

    @Resource
    private ThirdPartyAppService thirdPartyAppService;

    /**
     * 应用回到验证，推送suiteTicket，每5小时推送，可到后台开发手动触发
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @param body
     * @return
     */
    @ApiOperation("应用回到验证，推送suiteTicket，每5小时推送，可到后台开发手动触发")
    @PostMapping(value = "/sso/dingCallback")
    public Object dingCallback(@RequestParam(value = "signature") String signature,
        @RequestParam(value = "timestamp") Long timestamp, @RequestParam(value = "nonce") String nonce,
        @RequestBody(required = false) JSONObject body, @RequestParam(required = true) String token,
        @RequestParam(required = true) String encodingAesKey, @RequestParam(required = true) String suiteKey,
        @RequestParam(required = true) String suiteSecret) {
        log.debug("dingCallback-token={},encodingAesKey={},suiteKey={},suiteSecret={}", token, encodingAesKey, suiteKey,
            suiteSecret);
        if (StringUtils.isEmpty(token) || StringUtils.isEmpty(encodingAesKey) || StringUtils.isEmpty(suiteKey)
            || StringUtils.isEmpty(suiteSecret)) {
            return "fail:请在回到URL拼接Token（token）、数据加密密钥（encodingAesKey）、suiteKey、suiteSecret四个字段及值，如”?token=1&encodingAesKey=2&suiteKey=3&suiteSecret=4“。";
        }
        return thirdPartyAppService.dingCallback(signature, timestamp, nonce, body, token, encodingAesKey, suiteKey,
            suiteSecret);
    }

    @ApiOperation("获取JSAPI鉴权")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "url", value = "url", required = true, paramType = "query", dataType = "string"),
        @ApiImplicitParam(name = "corpId", value = "corpId", required = true, paramType = "query", dataType = "string"),
        @ApiImplicitParam(name = "suiteId", value = "suiteId", required = true, paramType = "query",
            dataType = "string"),})
    @GetMapping({"/jsap/get_authentication"})
    public JSONObject getJspaiAuthentication(String url, String corpId, String suiteId) {
        JSONObject data = new JSONObject();
        try {
            data = thirdPartyAppService.getJspaiAuthentication(url, corpId, suiteId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return data;
    }

    /**
     * 钉钉用户登录，显示当前登录的企业和用户
     *
     * @param authCode
     *            免登临时code
     */
    @ApiOperation(value = "钉钉用户登录，显示当前登录的企业和用户")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "authCode", value = "免登授权码", required = true, paramType = "query",
            dataType = "string"),
        @ApiImplicitParam(name = "corpId", value = "corpId", required = true, paramType = "query", dataType = "string"),
        @ApiImplicitParam(name = "suiteId", value = "suiteId", required = true, paramType = "query",
            dataType = "string"),})
    @GetMapping(value = "/sso/app_user")
    public JSONObject login(String authCode, String corpId, String suiteId) {
        JSONObject serviceResult = null;
        try {
            serviceResult = thirdPartyAppService.login(authCode, corpId, suiteId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return serviceResult;
    }

}
